package org.dev_common.file;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

public class FileUtils {
    public static Optional<byte[]> bytes(String path) {
        try {
            return Optional.of(Files.readAllBytes(Paths.get(path)));
        } catch (IOException e) {
            hookExceptions("", e);
            return Optional.empty();
        }
    }

    public static String string(String path) {
        return string(path, "utf-8");
    }

    public static String string(String path, String encode) {
        Optional<byte[]> bytes = bytes(path);
        try {
            return bytes.isPresent() ? new String(bytes.get(), encode) : "";
        } catch (UnsupportedEncodingException e) {
            hookExceptions("", e);
            return null;
        }
    }

    public static List<String> listString(String path) {
        return listString(path, "utf-8");
    }

    public static List<String> listString(String path, String encode) {
        try {
            return Files.readAllLines(Paths.get(path));
        } catch (IOException e) {
            hookExceptions("", e);
            return Collections.emptyList();
        }
    }
    // public static Table<R, C, V> asGuavaTable(String path, String split) {
    //
    // }

    public static void hookExceptions(String tag, Exception exp) {
        exp.printStackTrace();
    }

    public static void file(String content, String path) {
        try {
            Files.write(Paths.get(path), content.getBytes("utf-8"), StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
        } catch (IOException e) {
            hookExceptions("", e);
        }
    }

    public static void appendFile(String content, String path) {
        try {
            Files.write(Paths.get(path), content.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND,
                    StandardOpenOption.WRITE);
        } catch (IOException e) {
            hookExceptions("", e);
        }
    }
}
